package dth.bean;

import java.io.Serializable;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.view.JasperViewer;

import org.primefaces.event.CellEditEvent;
import org.primefaces.event.RowEditEvent;

import dth.dao.BookMovieDAO;
import dth.dao.OrderSetupBoxDAO;
import dth.dao.PaymentHistoryDAO;
import dth.dao.SetupBoxDAO;
import dth.entity.Account;
import dth.entity.BookMovie;
import dth.entity.OrderSetupBox;
import dth.entity.PaymentHistory;
import dth.entity.SetupBox;
import dth.utils.DthSessionConstant;
import dth.utils.DthUtil;

@ManagedBean(name = "ordersetupboxBean")
public class OrderSetupBoxBean {
	
	@ManagedProperty(value = "#{loginBean}")
	private LoginBean loginBean;// get session login bean
	private int setupbox_id;// use to insert delete
	private int status;
	private int quantity;
	private int setupboxorder_id;
	private List<OrderSetupBox> filteredOrders;
	private String PayType;
	private List<OrderSetupBox> listOrder = new ArrayList<OrderSetupBox>();
	
	public List<OrderSetupBox> getListOrder() {
		System.out.println("----status Order:" + status);
		OrderSetupBoxDAO dao = new OrderSetupBoxDAO();
		if (status == 2) {
			return dao.getListOrderSetupBox4();// get all cac order
		} else if (status == 0) {
			return dao.getListOrderSetupBox5(); // chua thanh toan
		} else if (status == 1) {
			return dao.getListOrderSetupBox6();
		}
		return listOrder;
	}

	public void setListOrder(List<OrderSetupBox> listOrder) {
		this.listOrder = listOrder;
	}
	
	public LoginBean getLoginBean() {
		return loginBean;
	}

	public void setLoginBean(LoginBean loginBean) {
		this.loginBean = loginBean;
	}

	public String getPayType() {
		return PayType;
	}

	public void setPayType(String payType) {
		PayType = payType;
	}

	public List<OrderSetupBox> getFilteredOrders() {
		return filteredOrders;
	}

	public void setFilteredOrders(List<OrderSetupBox> filteredOrders) {
		this.filteredOrders = filteredOrders;
	}

	public int getSetupboxorder_id() {
		return setupboxorder_id;
	}

	public void setSetupboxorder_id(int setupboxorder_id) {
		this.setupboxorder_id = setupboxorder_id;
	}

	public int getStatus() {
		Object object = DthUtil
				.getSession(DthSessionConstant.DTH_status_ordersetupbox_id);
		Account ac = DthUtil.getAccountDTH();
		if (object != null && ac != null & ac.getFkAdminId() > 0) {
			System.out.println("----getStatus:" + object.toString());
			status = Integer.parseInt(object.toString());
		}
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public int getSetupbox_id() {
		return setupbox_id;
	}

	public void setSetupbox_id(int setupbox_id) {
		this.setupbox_id = setupbox_id;
	}

	public OrderSetupBoxBean() {

		// TODO Auto-generated constructor stub
		
		System.out.println("---request url:"+DthUtil.getRequestURL());
		if(DthUtil.getRequestURL().contains("ordersetupbox_history.xhtml")){
			System.out.println("--vao day role:"+LoginBean.roleCode);
			if(LoginBean.roleCode!=1)
				DthUtil.navigateTo("welcome.xhtml");
		}
		
		System.out.println("--SetupBoxBean");
		Object objectAction = DthUtil.getRequest().getParameter("action");
		System.out.println("----------action:" + objectAction);
		if (objectAction != null) {
			if (objectAction.equals("insert")) {
				Object objectId = DthUtil.getRequest().getParameter(
						"setupbox_id");
				if (objectId != null)
					setupbox_id = Integer.parseInt(objectId.toString());
				System.out.println("---id insert order setupbox id:"
						+ setupbox_id);
			}
			if (objectAction.equals("delete")) {
				Object objectId = DthUtil.getRequest().getParameter(
						"setupboxorder_id");
				if (objectId != null)
					setupboxorder_id = Integer.parseInt(objectId.toString());
				System.out.println("---id insert order setupbox id:"
						+ setupboxorder_id);
			}
			if (objectAction.equals("update")) {

				Object objectId = DthUtil.getRequest().getParameter(
						"setupboxorder_id");
				System.out.println(quantity);
				if (objectId != null)
					setupboxorder_id = Integer.parseInt(objectId.toString());
				System.out.println("---id edit:" + setupboxorder_id);
				for (OrderSetupBox ordersetup : getListOrderSetupBox3()) {
					if (ordersetup.getId() == setupboxorder_id) {

						this.quantity = ordersetup.getQuantity();
					}
				}
			}
		}

		Object objectAction2 = DthUtil.getRequest().getParameter("PayType");
		if (objectAction2 != null) {
			this.PayType = objectAction2.toString();
		}
		System.out.println("payyyyyyyyyyyyyyyyyyy" + PayType);
	}

	public String getPayImgB() {
		Object objectAction = DthUtil.getRequest().getParameter("PayImgB");
		String img = "";
		if (objectAction != null) {
			img = objectAction.toString();
		}
		return img;
	}

	public List<OrderSetupBox> getListOrderSetupBox1() // da thanh toan
	{
		if (DthUtil.getAccountDTH() == null) {
			DthUtil.showMessage("Message", "You must login!");
			return null;
		} else {
			OrderSetupBoxDAO ordersetupboxDAO = new OrderSetupBoxDAO();
			List<OrderSetupBox> list = ordersetupboxDAO.getListOrderSetupBox1();
			return list;
		}
		// List<DetailOrderSetupBox> detail = new
		// ArrayList<DetailOrderSetupBox>();
		// SetupBoxDAO setupboxdao = new SetupBoxDAO();
		//
		// OrderSetupBoxDAO ordersetupboxDAO=new OrderSetupBoxDAO();
		// List<OrderSetupBox> listOderSetupBox =
		// ordersetupboxDAO.getListOrderSetupBox1();
		// for (OrderSetupBox orderSetupBox : listOderSetupBox) {
		// int i = orderSetupBox.getFkSetupBox();
		// System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaiiiiiiiiiiiiiiiiiiiii ++++ "
		// +i);
		// SetupBox set = setupboxdao.getSetupBox(i);
		//
		// DetailOrderSetupBox temp = new DetailOrderSetupBox();
		// temp.setId(orderSetupBox.getId());
		// temp.setDateInsert(orderSetupBox.getDateInsert());
		// temp.setPriceSTB(set.getPrice());
		// temp.setQuantity(orderSetupBox.getQuantity());
		// temp.setTypeSTB(set.getType());
		// detail.add(temp);
		// }
		// return detail;
	}

	public java.util.List<OrderSetupBox> getListOrderSetupBox2() // chua thanh
																	// toan
	{
		if (DthUtil.getAccountDTH() == null) {
			DthUtil.showMessage("Message", "You must login!");
			return null;
		} else {
			OrderSetupBoxDAO ordersetupboxDAO = new OrderSetupBoxDAO();
			List<OrderSetupBox> list = ordersetupboxDAO.getListOrderSetupBox2();
			return list;
		}
	}

	public java.util.List<OrderSetupBox> getListOrderSetupBox3() // get all
	{
		OrderSetupBoxDAO ordersetupboxDAO = new OrderSetupBoxDAO();
		List<OrderSetupBox> list = ordersetupboxDAO.getListOrderSetupBox3();
		return list;
	}

	public void insertOrder() {
		if (DthUtil.getAccountDTH() == null)
			DthUtil.showMessage("Message", "You must login!");
		else {
			if (quantity <= 0) {
				DthUtil.showMessage("Message", "Bạn phải nhập số lượng > 0");
			} else {
				OrderSetupBox order = new OrderSetupBox();
				OrderSetupBoxDAO dao = new OrderSetupBoxDAO();
				Account ac = new Account();
				ac = DthUtil.getAccountDTH();
				java.util.Date date = new java.util.Date();// lay ngay hien tai
				order.setDateInsert(new Date(date.getTime()));
				order.setId(0);
				order.setFkDealerId(ac.getFkDealerId());
				order.setFkDistributorId(ac.getFkDistributorId());// set cung'
				System.out
						.println("idddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd  "
								+ setupbox_id);
				order.setFkSetupBox(setupbox_id);
				order.setFkUserId(ac.getFkUserId());
				order.setQuantity(quantity);

				Object objectId = DthUtil.getRequest().getParameter(
						"setupbox_type");
				String type = "";
				System.out.println("typeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee "
						+ type);
				if (objectId != null)
					type = objectId.toString();
				order.setTypeSTB(type);
				System.out.println("typeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee "
						+ type);
				Object objectId1 = DthUtil.getRequest().getParameter(
						"setupbox_price");
				double temp = 0;
				if (objectId1 != null)
					temp = Double.parseDouble(objectId1.toString());
				order.setPriceSTB(temp);
				System.out.println("typeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee "
						+ temp);
				order.setStatus(0); // chua thanh toan
				int count = 0;
				if (quantity <= 0) {
					DthUtil.showMessage("Thông báo",
							"Đặt hàng thất bại, số lượng phải nhiều hơn 0");
				}
				count = dao.insert(order);
				if (count == 1)
					DthUtil.showMessage("Thông báo", "Đặt hàng thành công");
				if (count == 2)
					DthUtil.showMessage("Thông báo",
							"Đã có setupbox trong giỏ hàng!");
				if (count <= 0)
					DthUtil.showMessage("Thông báo", "Đặt hàng thất bại");
			}
		}
	}

	public void updateQUA() {
		OrderSetupBoxDAO order = new OrderSetupBoxDAO();
		order.updateQuantity(setupboxorder_id, quantity);
	}

	public void delete() {
		
		Object objectId = DthUtil.getRequest().getParameter("setupboxorder_id");
		if (objectId != null)
			setupboxorder_id = Integer.parseInt(objectId.toString());
		OrderSetupBoxDAO ordersetupboxDAO = new OrderSetupBoxDAO();
		System.out.println("orderbean delete id : "+ setupboxorder_id);
		int count = ordersetupboxDAO.delete(setupboxorder_id);
		if (count > 0)
			DthUtil.showMessage("Thông báo", "Xóa thành công");
		else
			DthUtil.showMessage("Thông báo", "Xóa thất bại");
	}

	public void onEdit(RowEditEvent event) {
		if (quantity <= 0) {
			DthUtil.showMessage("Thông báo", "Ban phai nhap lon hon 0");
		} else {
			OrderSetupBox order = (OrderSetupBox) event.getObject();
			OrderSetupBoxDAO orderDao = new OrderSetupBoxDAO();
			orderDao.updateQuantity(order.getId(), quantity);
			DthUtil.showMessage("Thông báo", "Update Quantity = " + quantity);
		}
	}

	public void onCancel(RowEditEvent event) {
		DthUtil.showMessage("Thông báo", "Okay");
	}

	public void directShowCart() {
		if (DthUtil.getAccountDTH() != null)
			DthUtil.navigateTo("showsetupbox_order.xhtml");
		else
			DthUtil.showMessage("Message", "You must login!");
	}

	public String Total() {
		double sum = 0;
		OrderSetupBoxDAO ordersetupboxDAO = new OrderSetupBoxDAO();
		List<OrderSetupBox> list = ordersetupboxDAO.getListOrderSetupBox2();
		for (OrderSetupBox ordersetup : list) {
			sum = sum + (ordersetup.getQuantity() * ordersetup.getPriceSTB());
		}

		return DthUtil.getFormatedNumber(sum);
	}

	public void payment() {
		Account ac = DthUtil.getAccountDTH();
		OrderSetupBoxDAO or = new OrderSetupBoxDAO();
		or.updateStatus(ac.getFkDealerId(), ac.getFkDistributorId(),
				ac.getFkUserId());
		DthUtil.showMessage("Thông báo!", "Thanh toán thành công.");
	}

	public void changeUserChooser() {
		System.out.println("---user id:" + status);
		DthUtil.setSession(DthSessionConstant.DTH_status_ordersetupbox_id,
				status);
	}

	// / Test report

	public static JasperDesign jasperDesign;
	public static JasperPrint jasperPrint;
	public static JasperReport jasperReport;

	public void test() {
		try {
			ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
			System.out.println("try");
			String reporte = extContext.getRealPath("//report//ReportOrderSetupBox.jrxml");
			Map<String, Object> param = new HashMap<String, Object>();
			Object object = DthUtil
					.getSession(DthSessionConstant.DTH_status_ordersetupbox_id);
			
			if (object == null) {
				param.put("Month", "Unpaid");
			} else {
				int status = Integer.parseInt(object.toString());

				if (status == 2) {
					param.put("Month", "All");
				} else if (status == 0) {
					param.put("Month", "Unpaid");
				} else if (status == 1) {
					param.put("Month", "Paid");
				}

			}
			
			JasperReport jasperreport = JasperCompileManager
					.compileReport(reporte);
			JasperPrint jasperPrint = JasperFillManager.fillReport(
					jasperreport, param, new JRBeanArrayDataSource(
							generateArray()));
			JasperViewer.viewReport(jasperPrint, false);
		} catch (JRException e) {
			e.printStackTrace();
		}
	}

	// public static java.util.Collection generateCollection() {
	// // Creates the collection
	// java.util.Vector collection = new java.util.Vector();
	//
	// // Adds the values in the bean and adds it into the collection
	// collection.add(new PersonBean("Ted", 20));
	// collection.add(new PersonBean("Jack", 34));
	// collection.add(new PersonBean("Bob", 56));
	// collection.add(new PersonBean("Alice", 12));
	// collection.add(new PersonBean("Robin", 22));
	// collection.add(new PersonBean("Peter", 28));
	//
	// // returns the collection of beans.
	// return collection;
	// }

	public static OrderSetupBox[] generateArray() {
		Object object = DthUtil
				.getSession(DthSessionConstant.DTH_status_ordersetupbox_id);
		OrderSetupBoxDAO dao = new OrderSetupBoxDAO();
		List<OrderSetupBox> list = new ArrayList<OrderSetupBox>();
		if (object == null) {
			list = dao.getListOrderSetupBox5();
		} else {
			int status = Integer.parseInt(object.toString());

			if (status == 2) {
				list = dao.getListOrderSetupBox4();// get all cac order
			} else if (status == 0) {
				list = dao.getListOrderSetupBox5(); // chua thanh toan
			} else if (status == 1) {
				list = dao.getListOrderSetupBox6();
			}

		}
		OrderSetupBox lst[] = new OrderSetupBox[list.size()];
		for (int i = 0; i < list.size(); i++) {
			lst[i] = list.get(i);
		}
		// returns the Array of beans.
		return lst;

	}
}
